<template>
  <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <div class="articleList">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <Articlelists :list="list" :timestamp="timestamp"></Articlelists>
      </van-list>
    </div>
  </van-pull-refresh>
</template>

<script>
import { getArticleLists } from '@/api/homepage/articleLists.js'
import Articlelists from '@/components/ArticleList'
import { getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      isLoading: false
    }
  },
  props: ['id'],
  mounted () {},
  methods: {
    // 下拉刷新
    async onRefresh () {
      const params = {
        channel_id: this.id,
        timestamp: Date.now(),
        with_top: 1
      }
      try {
        // 异步更新数据
        const {
          data: { data: res }
        } = await getArticleLists(params)
        this.list = [...res.results, ...this.list]
        // 是否已经加载完
        this.$toast('刷新成功')
        this.isLoading = false
      } catch (error) {
        console.log(error)
        this.$toast('刷新失败')
        this.isLoading = false
      }
    },
    // 下滑刷新
    async onLoad () {
      const params = {
        channel_id: this.id,
        timestamp: this.timestamp,
        with_top: 1
      }
      if (getItem('history')) {
        params.timestamp = getItem('history')
        // 删除本地防止下滑时永远是这个时间戳
        localStorage.removeItem('history')
      }
      try {
        // 异步更新数据
        const {
          data: { data: res }
        } = await getArticleLists(params)
        this.list = [...this.list, ...res.results]
        if (res.results.length === 0) {
          // 是否已经加载完
          this.finished = true
          this.loading = true
        } else {
          // 更新时间戳
          this.timestamp = res.pre_timestamp
          // 加载状态是否结束
          this.loading = false
          this.finished = false
        }
      } catch (error) {
        console.log(error)
        this.finished = true
      }
    }
  },
  components: {
    Articlelists
  }
}
</script>

<style lang="less" scoped>
.articleList {
  height: 79vh;
  overflow-y: auto;
}
</style>
